const router = require('koa-router')()
const url = require('url')
let Navs = require('../../models/Navs')
let resData

router.use(async (ctx, next) => {
  let pathName = url.parse(ctx.request.url).pathname.substring(1)
  resData = {
    code: 0,
    message: '',
    data: {}
  }
  if (ctx.session.userInfo) {
    await next()
  } else {
    if(pathName === 'blog/api/sortNavList') {
      await next()
    } else {
      resData.code = 9999
      resData.message = '登录过期'
      ctx.body = resData
    }
  }
})

// 后台导航列表查询
router.get('/navList', async (ctx) => {
  let navList = await Navs.find({}).then(data => {
    return data
  })
  if (navList.length > 0) {
    resData.code = 0
    resData.message = '查询成功'
    resData.data.list = navList
    ctx.body = resData
  }
})
// 新增导航或者修改导航
router.post('/handleNav', async (ctx) => {
  let {_id, nav_name, url, status, order} = ctx.request.body
  if (_id === '') {
    let nav = new Navs({
      nav_name,
      url,
      status,
      order
    })

    let result = await nav.save().then(res => {
      return res
    })
    if (result) {
      resData.code = 0
      resData.message = '新增成功'
      ctx.body = resData
    } else {
      resData.code = 1
      resData.message = '新增失败'
      ctx.body = resData
    }
  } else {
    let result = await Navs.findByIdAndUpdate(_id, {
      nav_name,
      url,
      status,
      order
    }).then(res => {
      return res
    })
    if (result) {
      resData.code = 0
      resData.message = '修改成功'
      ctx.body = resData
    } else {
      resData.code = 1
      resData.message = '修改失败'
      ctx.body = resData
    }
  }
})
// 删除导航
router.post('/removeNav', async (ctx) => {
  let { _id } = ctx.request.body
  let result = await Navs.findByIdAndRemove(_id).then(res => {
    return res
  })
  if (result) {
    resData.code = 0
    resData.message = '删除成功'
    ctx.body = resData
  } else {
    resData.code = 1
    resData.message = '删除失败'
    ctx.body = resData
  }
})
//前台查询排序后的导航
router.get('/sortNavList', async (ctx) => {
  let result = await Navs.find({status: 1}).sort({ order: 1 }).then(res => {
    return res
  })
  resData.code = 0
  resData.message = '查询成功'
  resData.data.list = result
  ctx.body = resData
})

module.exports = router.routes()
